package com.dianban.service.impl;


import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.dao.FacePayStoreConsumeLogDao;
import com.dianban.entity.*;
import com.dianban.service.*;
import com.dianban.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户业务实现层
 * <p>
 * Created by bysocket on 07/02/2017.
 */
@Service
@Transactional(readOnly = true)
public class FacePayStoreConsumeLogServiceImpl implements FacePayStoreConsumeLogService {

    @Autowired
    private FacePayStoreConsumeLogDao facePayStoreConsumeLogDao;
    @Autowired
    private ShoproOrderService shoproOrderService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private FacePayCommissionLogService facePayCommissionLogService;
    @Autowired
    private ShopUserService shopUserService;
    @Autowired
    private FacePayDeviceLogService facePayDeviceLogService;
    @Autowired
    private CardService cardService;
    @Autowired
    private FacePayStoreOrderShareLogService facePayStoreOrderShareLogService;

    @Override
    public FacePayStoreConsumeLog findById(String id) {
        return facePayStoreConsumeLogDao.findById(id);
    }

    @Override
    public List<FacePayStoreConsumeLog> findList(Long userId, Long storeId, String type) {
        return facePayStoreConsumeLogDao.findList(userId, storeId, type);
    }

    @Override
    @Transactional(readOnly = false)
    public int insert(FacePayStoreConsumeLog facePayStoreConsumeLog) {
        facePayStoreConsumeLog.setCreatetime(System.currentTimeMillis() / 1000);
        return facePayStoreConsumeLogDao.insert(facePayStoreConsumeLog);
    }

    @Override
    @Transactional(readOnly = false)
    public ResultVo verify(FacePayStoreConsumeLog facePayStoreConsumeLog, Long shopUserId) {
        Map<String, Object> resultMap = new HashMap<>();
        int count = 0;
        Integer remainVerifyCount = 0;
        String errorInfo = "";
        ShopUser shopUser = shopUserService.findById(shopUserId);
        Long storeId = shopUser.getStoreId();
        // 调用开关
        ResultVo resultVo = facePayDeviceLogService.deviceSwitch(1, storeId, null);
        if (!"200".equals(resultVo.getCode())) {
            return resultVo;
        }
        if (facePayStoreConsumeLog.getOnlineOrderId() != null) {
            ShoproOrder shoproOrder = shoproOrderService.findById(facePayStoreConsumeLog.getOnlineOrderId());
            if ("10".equals(facePayStoreConsumeLog.getType())) {
                count = shoproOrderService.updateVerify(shoproOrder.getId(), shoproOrder.getHasVerifyCount(), null);
                remainVerifyCount = shoproOrder.getCanVerifyCount() - shoproOrder.getHasVerifyCount() - 1;
            } else if ("30".equals(facePayStoreConsumeLog.getType())) {
                count = shoproOrderService.updateVerify(shoproOrder.getId(), null, shoproOrder.getTakenewHasVerifyCount());
            }
            errorInfo = "核销线上订单异常，订单id：" + shoproOrder.getId();
        } else if (facePayStoreConsumeLog.getOfflineOrderId() != null) {
            FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findById(facePayStoreConsumeLog.getOfflineOrderId());
            // 399每天只能核销一次
            if (facePayStoreOrder.getMoney().setScale(2, BigDecimal.ROUND_DOWN)
                    .compareTo(new BigDecimal("399").setScale(2, BigDecimal.ROUND_DOWN)) == 0) {
                List<FacePayStoreConsumeLog> facePayStoreConsumeLogs = facePayStoreConsumeLogDao.findByParams(DateUtils.generateDayBegin(), DateUtils.generateDayEnd(), facePayStoreOrder.getUserId(), facePayStoreOrder.getId());
                if (!CollectionUtils.isEmpty(facePayStoreConsumeLogs)) {
                    return ResultVo.error(ResultCode.ERROR, "今日已使用过");
                }
            }
            if ("20".equals(facePayStoreConsumeLog.getType())) {
                count = facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
                remainVerifyCount = facePayStoreOrder.getCanVerifyCount() - facePayStoreOrder.getHasVerifyCount() - 1;
            } else if ("30".equals(facePayStoreConsumeLog.getType())) {
                count = facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), null, facePayStoreOrder.getTakenewHasVerifyCount());
            } else if ("40".equals(facePayStoreConsumeLog.getType())) {
                count = facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
            }
            errorInfo = "核销线下订单异常，订单id：" + facePayStoreOrder.getId();
        }
        if (count > 0) {
            facePayStoreConsumeLog.setCreatetime(System.currentTimeMillis() / 1000);
            facePayStoreConsumeLogDao.insert(facePayStoreConsumeLog);
            //清分
            facePayCommissionLogService.commission(facePayStoreConsumeLog, shopUserId);
            resultMap.put("remainVerifyCount", remainVerifyCount);
            return ResultVo.success(resultMap);
        }
        return ResultVo.error(ResultCode.ERROR, errorInfo);
    }

    @Override
    @Transactional(readOnly = false)
    public ResultVo verifyCard(FacePayStoreConsumeLog facePayStoreConsumeLog) {
        Map<String, Object> resultMap = new HashMap<>();
        int count = 0;
        Integer remainVerifyCount = 0;
        String errorInfo = "核销卡号异常";
        if (facePayStoreConsumeLog.getCardId() != null) {
            Card card = cardService.findById(facePayStoreConsumeLog.getCardId());
            if (card.getCanVerify() < card.getHasVerify()) {
                return ResultVo.error(ResultCode.ERROR, "卡号核销已使用完");
            }
            // 调用开关
            ResultVo resultVo = facePayDeviceLogService.deviceSwitch(1, facePayStoreConsumeLog.getStoreId(), null);
            if (!"200".equals(resultVo.getCode())) {
                return resultVo;
            }
            count = cardService.updateVerify(card.getId(), card.getHasVerify());
            remainVerifyCount = card.getCanVerify() - card.getHasVerify() - 1;
            errorInfo = "核销卡号异常，卡号id：" + card.getId();
        }
        if (count > 0) {
            facePayStoreConsumeLog.setCreatetime(System.currentTimeMillis() / 1000);
            facePayStoreConsumeLogDao.insert(facePayStoreConsumeLog);

            resultMap.put("remainVerifyCount", remainVerifyCount);
            return ResultVo.success(resultMap);
        }
        return ResultVo.error(ResultCode.ERROR, errorInfo);
    }

    @Override
    public List<FacePayStoreConsumeLog> findByParams(String generateDayBegin, String generateDayEnd, Long userId, Long offlineOrderId) {
        return facePayStoreConsumeLogDao.findByParams(generateDayBegin, generateDayEnd, userId, offlineOrderId);
    }

    @Override
    public List<FacePayStoreConsumeLog> find(Long storeId, Long beforeTime, Long nowTime) {
        return facePayStoreConsumeLogDao.find(storeId, beforeTime, nowTime);
    }

    @Override
    @Transactional(readOnly = false)
    public ResultVo verifyShare(FacePayStoreConsumeLog facePayStoreConsumeLog) {
        Map<String, Object> resultMap = new HashMap<>();
        String errorInfo = "分享核销异常";
        if (facePayStoreConsumeLog.getShareLogId() != null) {
            FacePayStoreOrderShareLog shareLog = facePayStoreOrderShareLogService.findById(facePayStoreConsumeLog.getShareLogId());
            if (!"1".equals(shareLog.getStatus())) {
                return ResultVo.error(ResultCode.ERROR, "分享核销已使用完");
            }
            // 调用开关
            ResultVo resultVo = facePayDeviceLogService.deviceSwitch(1, facePayStoreConsumeLog.getStoreId(), null);
            if (!"200".equals(resultVo.getCode())) {
                return resultVo;
            }
            facePayStoreOrderShareLogService.update(facePayStoreConsumeLog.getShareLogId(), "2", null, null);
            facePayStoreConsumeLog.setCreatetime(System.currentTimeMillis() / 1000);
            facePayStoreConsumeLogDao.insert(facePayStoreConsumeLog);
            return ResultVo.success(resultMap);
        }
        return ResultVo.error(ResultCode.ERROR, errorInfo);
    }
}
